package com.chuangyang.fixboxmaster.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Response;
import com.bumptech.glide.Glide;
import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxmaster.AppData;
import com.chuangyang.fixboxmaster.BuildConfig;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.B2BOrderDetail;
import com.chuangyang.fixboxmaster.bean.BaseInfo;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.widgets.MyProgressDlg;
import com.chuangyang.fixboxmaster.utils.PrefUtils;
import com.google.gson.Gson;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ChosenImages;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.HttpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by vanshu on 15/10/15 11:26.
 */
public class ReceiveCodeActivity extends BaseActivity implements View.OnClickListener,ImageChooserListener {
    private EditText mEditUserCode;
    private String orderId;
    private String phoneNumber;
    private final static String TAG = "ICA";
    private String originalFilePath;
    private String thumbnailFilePath;
    private String thumbnailSmallFilePath;

    private ImageView mBtnFapiao;
    private ImageView mBtnAnzhuang;
    private ImageView mBtnTiaoXingMa;
    private int currentPosition=-1;

    private ArrayList<String> mPicPathList;
    private MyProgressDlg mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("验证完成");
        setContentView(R.layout.activity_receive_code);
        orderId = getIntent().getStringExtra("orderId");
        phoneNumber=getIntent().getStringExtra("number");
        mEditUserCode = (EditText) findViewById(R.id.et_user_code);
        Button mBtnRequestCode = (Button) findViewById(R.id.btn_request_code);
        Button mBtnVerifyCode = (Button) findViewById(R.id.btn_verify_code);
        mBtnRequestCode.setOnClickListener(this);
        mBtnVerifyCode.setOnClickListener(this);

        mBtnFapiao = (ImageView) findViewById(R.id.btn_fapiao);
        mBtnFapiao.setOnClickListener(this);

        mBtnAnzhuang = (ImageView) findViewById(R.id.btn_anzhuangxianchang);
        mBtnAnzhuang.setOnClickListener(this);

        mBtnTiaoXingMa = (ImageView) findViewById(R.id.btn_tiaoxingma);
        mBtnTiaoXingMa.setOnClickListener(this);
        mPicPathList=new ArrayList<>();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_request_code:
                HashMap<String, String> param1 = new HashMap<>();
                param1.put("id", orderId);
                addRequest(new GsonRequest<>(FixBoxApi.B2B_REQUEST_CODE, param1, BaseInfo.class, response1Listener));
                break;
            case R.id.btn_verify_code:
                if (validate()) {
                    uploadMedia();
                }
                break;
            case R.id.btn_fapiao:
                takePicture();
                currentPosition=1;
                break;
            case R.id.btn_anzhuangxianchang:
                takePicture();
                currentPosition=2;
                break;

            case  R.id.btn_tiaoxingma:
                takePicture();
                currentPosition=3;
                break;
        }
    }

    private Response.Listener<BaseInfo> response1Listener = new Response.Listener<BaseInfo>() {
        @Override
        public void onResponse(BaseInfo response) {
            if(response.success==1){
                Toast.makeText(getApplicationContext(), "验证码稍后会发送到您到手机，请注意查收", Toast.LENGTH_SHORT).show();
            }
        }
    };


    public boolean validate() {
        if (mEditUserCode.getText().toString().length() == 0) {
            Toast.makeText(getApplicationContext(), "请输入验证码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.b2b_order_detail_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_online_service:
                StringUtils.dialPhone(ReceiveCodeActivity.this, phoneNumber);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private ImageChooserManager imageChooserManager;
    private String filePath;
    private int chooserType;


    private void takePicture() {
        chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
        imageChooserManager = new ImageChooserManager(this,ChooserType.REQUEST_CAPTURE_PICTURE, true);
        imageChooserManager.setImageChooserListener(this);
        try {
            filePath = imageChooserManager.choose();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "OnActivityResult");
        Log.i(TAG, "File Path : " + filePath);
        Log.i(TAG, "Chooser Type: " + chooserType);
        if (resultCode == RESULT_OK
                && (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
            if (imageChooserManager == null) {
                reinitializeImageChooser();
            }
            imageChooserManager.submit(requestCode, data);
        } else {
        }
    }

    @Override
    public void onImageChosen(final ChosenImage image) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                originalFilePath = image.getFilePathOriginal();
                thumbnailFilePath = image.getFileThumbnail();
                thumbnailSmallFilePath = image.getFileThumbnailSmall();
                if (image != null) {
                    Log.i(TAG, "Chosen Image: Is not null");
                    if(currentPosition==1){
                        loadImage(mBtnFapiao, image.getFileThumbnail());
                    }else  if(currentPosition==2){
                        loadImage(mBtnAnzhuang, image.getFileThumbnail());
                    }else if(currentPosition==3){
                        loadImage(mBtnTiaoXingMa, image.getFileThumbnail());
                    }
                    mPicPathList.add(thumbnailSmallFilePath);
                } else {
                    Log.i(TAG, "Chosen Image: Is null");
                }
            }
        });
    }

    @Override
    public void onImagesChosen(final ChosenImages images) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "On Images Chosen: " + images.size());
                onImageChosen(images.getImage(0));
            }
        });
    }

    private void loadImage(ImageView iv, final String path) {
        Glide.with(AppData.getContext()).load(path).
                placeholder(R.drawable.ic_order_detail_empty_view).centerCrop().crossFade().into(iv);
    }

    @Override
    public void onError(final String reason) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "OnError: " + reason);
                Toast.makeText(ReceiveCodeActivity.this, reason,
                        Toast.LENGTH_LONG).show();
            }
        });
    }

    private void reinitializeImageChooser() {
        imageChooserManager = new ImageChooserManager(this, chooserType, true);
        Bundle bundle = new Bundle();
        bundle.putBoolean(Intent.EXTRA_ALLOW_MULTIPLE, true);
        imageChooserManager.setExtras(bundle);
        imageChooserManager.setImageChooserListener(this);
        imageChooserManager.reinitialize(filePath);
    }


    private void uploadMedia(){
        showLoadingView();
        // 需要post的值
        RequestParams params = new RequestParams();
        if(PrefUtils.getString(PrefUtils.ACCESS_TOKEN)!=null){
            params.addBodyParameter(PrefUtils.ACCESS_TOKEN, PrefUtils.getString(AppData.getContext(), PrefUtils.ACCESS_TOKEN));
        }
        for(int i=0;i<mPicPathList.size();i++){
            params.addBodyParameter("img"+(i+1),new File(mPicPathList.get(i)));
        }
        params.addBodyParameter("id",""+orderId);
        params.addBodyParameter("varifyCode",""+mEditUserCode.getText().toString());
        HttpUtils http = new HttpUtils(6*1000);
        http.send(HttpRequest.HttpMethod.POST,FixBoxApi.B2B_VERIFY_CODE,params,new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Gson gson = new Gson();
                B2BOrderDetail info = gson.fromJson(String.valueOf(response.result),B2BOrderDetail.class);
                if (info.success == 1)
                {
                    if (BuildConfig.DEBUG)
                    Toast.makeText(ReceiveCodeActivity.this,"上传成功!",Toast.LENGTH_LONG).show();
                    finish();
                }
                else
                {
                    Toast.makeText(ReceiveCodeActivity.this,""+info.msg,Toast.LENGTH_LONG).show();
                }
                dismissLoadingView();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(ReceiveCodeActivity.this,""+s,Toast.LENGTH_LONG).show();
                dismissLoadingView();
            }
        });

    }




    public void showLoadingView() {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {

            public void run() {
                if(mProgressDialog==null){
                    mProgressDialog = new MyProgressDlg(ReceiveCodeActivity.this, R.style.dialog2);
                    mProgressDialog.setCanceledOnTouchOutside(false);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();}
            }
        });
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissLoadingView();
            }
        },6*1000*1);
    }


    /**
     * 隐藏加载框
     */
    public void dismissLoadingView() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }
}
